import React, { useEffect, useRef, memo } from "react";
import resumeData from "./data/resume.json";
import styles from "./Resume.module.less";
import type { Skill, Project, Experience, Education } from "./types/resume";

// 技能进度条组件
interface SkillBarProps {
  skill: Skill;
}

const SkillBar: React.FC<SkillBarProps> = memo(({ skill }) => {
  const progressRef = useRef<HTMLDivElement>(null);
  const [isVisible, setIsVisible] = React.useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { threshold: 0.1 }
    );

    if (progressRef.current) {
      observer.observe(progressRef.current);
    }

    return () => observer.disconnect();
  }, []);

  return (
    <div className={styles.skillItem} aria-label={`技能: ${skill.name}, 水平: ${skill.level}%`}>
      <div className={styles.skillHeader}>
        <span className={styles.skillName}>{skill.name}</span>
        <span className={styles.skillLevel} aria-label={`${skill.level}%`}>
          {skill.level}%
        </span>
      </div>
      <div className={styles.skillBar} role="progressbar" aria-valuenow={skill.level} aria-valuemin={0} aria-valuemax={100}>
        <div
          ref={progressRef}
          className={styles.skillProgress}
          style={{
            width: isVisible ? `${skill.level}%` : "0%",
            transition: "width 0.8s ease-in-out",
          }}
          aria-hidden="true"
        />
      </div>
    </div>
  );
});

SkillBar.displayName = "SkillBar";

// 项目卡片组件
interface ProjectCardProps {
  project: Project;
}

const ProjectCard: React.FC<ProjectCardProps> = memo(({ project }) => (
  <article className={styles.projectCard}>
    <div className={styles.projectHeader}>
      <h3 className={styles.projectName}>{project.name}</h3>
      <span className={styles.projectRole} aria-label={`角色: ${project.role}`}>
        {project.role}
      </span>
    </div>
    <p className={styles.projectDescription}>{project.description}</p>
    {project.achievements && project.achievements.length > 0 && (
      <div className={styles.projectHighlights}>
        {project.achievements.map((achievement, index) => (
          <div key={index} className={styles.highlightItem}>
            • {achievement}
          </div>
        ))}
      </div>
    )}
    {project.technologies && project.technologies.length > 0 && (
      <div className={styles.projectTech} aria-label="使用的技术">
        {project.technologies.map((tech, index) => (
          <span key={index} className={styles.techTag}>
            {tech}
          </span>
        ))}
      </div>
    )}
    <div className={styles.projectMeta}>
      <span className={styles.projectDate} aria-label={`项目周期: ${project.duration}`}>
        {project.duration}
      </span>
    </div>
    {project.url && (
      <div className={styles.projectLinks}>
        <a
          href={project.url}
          target="_blank"
          rel="noopener noreferrer"
          className={styles.projectLink}
          aria-label={`查看项目 ${project.name}`}
        >
          查看项目
        </a>
      </div>
    )}
  </article>
));

ProjectCard.displayName = "ProjectCard";

// 工作经验组件
interface ExperienceCardProps {
  experience: Experience;
}

const ExperienceCard: React.FC<ExperienceCardProps> = memo(({ experience }) => (
  <article className={styles.experienceCard}>
    <div className={styles.experienceHeader}>
      <div className={styles.experienceTitle}>
        <h3 className={styles.position}>{experience.position}</h3>
        <h4 className={styles.company}>{experience.company}</h4>
      </div>
      <div className={styles.experienceMeta}>
        <span className={styles.date} aria-label={`工作周期: ${experience.duration}`}>
          {experience.duration}
        </span>
        <span className={styles.location} aria-label={`工作地点: ${experience.location}`}>
          {experience.location}
        </span>
      </div>
    </div>
    {experience.responsibilities && experience.responsibilities.length > 0 && (
      <div className={styles.achievements}>
        {experience.responsibilities.map((responsibility, index) => (
          <div key={index} className={styles.achievementItem}>
            • {responsibility}
          </div>
        ))}
      </div>
    )}
  </article>
));

ExperienceCard.displayName = "ExperienceCard";

// 教育背景组件
interface EducationCardProps {
  education: Education;
}

const EducationCard: React.FC<EducationCardProps> = memo(({ education }) => {
  const dateDisplay = education.duration || 
    (education.startDate && education.endDate 
      ? `${education.startDate} - ${education.endDate}` 
      : "");

  return (
    <article className={styles.educationCard}>
      <div className={styles.educationHeader}>
        <h3 className={styles.school}>{education.school}</h3>
        {dateDisplay && (
          <span className={styles.date} aria-label={`教育周期: ${dateDisplay}`}>
            {dateDisplay}
          </span>
        )}
      </div>
      <div className={styles.educationDetails}>
        <p className={styles.degree}>
          {education.level} · {education.degree}
        </p>
        {education.gpa && (
          <p className={styles.gpa} aria-label={`GPA: ${education.gpa}`}>
            GPA: {education.gpa}
          </p>
        )}
      </div>
      {education.achievements && education.achievements.length > 0 && (
        <div className={styles.achievements}>
          {education.achievements.map((achievement, index) => (
            <div key={index} className={styles.achievementItem}>
              • {achievement}
            </div>
          ))}
        </div>
      )}
    </article>
  );
});

EducationCard.displayName = "EducationCard";

// 主简历组件
const Resume: React.FC = () => {
  const { personalInfo, education, experience, skills, projects } = resumeData as import("./types/resume").ResumeData;

  return (
    <main className={styles.resumeContainer} role="main" aria-label="个人简历">
      {/* 头部个人信息 */}
      <header className={styles.resumeHeader}>
        <div className={styles.headerContent}>
          <div className={styles.infoSection}>
            <h1 className={styles.name}>{personalInfo.name}</h1>
            <h2 className={styles.title}>{personalInfo.title}</h2>
            <p className={styles.summary}>{personalInfo.summary}</p>
            <div className={styles.contactInfo} role="list" aria-label="联系方式">
              <div className={styles.contactItem} role="listitem">
                <span className={styles.icon} aria-hidden="true">📧</span>
                <a 
                  href={`mailto:${personalInfo.contact.email}`}
                  aria-label={`发送邮件到 ${personalInfo.contact.email}`}
                >
                  {personalInfo.contact.email}
                </a>
              </div>
              <div className={styles.contactItem} role="listitem">
                <span className={styles.icon} aria-hidden="true">📱</span>
                <span aria-label={`电话号码: ${personalInfo.contact.phone}`}>
                  {personalInfo.contact.phone}
                </span>
              </div>
              <div className={styles.contactItem} role="listitem">
                <span className={styles.icon} aria-hidden="true">📍</span>
                <span aria-label={`所在地: ${personalInfo.contact.location}`}>
                  {personalInfo.contact.location}
                </span>
              </div>
              <div className={styles.contactItem} role="listitem">
                <span className={styles.icon} aria-hidden="true">🌐</span>
                <a
                  href={personalInfo.contact.website}
                  target="_blank"
                  rel="noopener noreferrer"
                  aria-label={`访问个人网站: ${personalInfo.contact.website}`}
                >
                  {personalInfo.contact.website}
                </a>
              </div>
              {personalInfo.contact.github && (
                <div className={styles.contactItem} role="listitem">
                  <span className={styles.icon} aria-hidden="true">💻</span>
                  <a
                    href={personalInfo.contact.github}
                    target="_blank"
                    rel="noopener noreferrer"
                    aria-label={`访问 GitHub 主页`}
                  >
                    GitHub
                  </a>
                </div>
              )}
              {personalInfo.contact.linkedin && (
                <div className={styles.contactItem} role="listitem">
                  <span className={styles.icon} aria-hidden="true">💼</span>
                  <a
                    href={personalInfo.contact.linkedin}
                    target="_blank"
                    rel="noopener noreferrer"
                    aria-label={`访问 LinkedIn 主页`}
                  >
                    LinkedIn
                  </a>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      <div className={styles.resumeContent}>
        {/* 技能 */}
        <section className={styles.section} aria-labelledby="skills-title">
          <h2 id="skills-title" className={styles.sectionTitle}>专业技能</h2>
          <div className={styles.skillsGrid}>
            {skills.map((skillCategory, index) => (
              <div key={index} className={styles.skillCategory}>
                <h3 className={styles.categoryTitle}>{skillCategory.category}</h3>
                <div className={styles.skillsList} role="list">
                  {skillCategory.items.map((skill, skillIndex) => (
                    <SkillBar key={skillIndex} skill={skill} />
                  ))}
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* 工作经验 */}
        <section className={styles.section} aria-labelledby="experience-title">
          <h2 id="experience-title" className={styles.sectionTitle}>工作经验</h2>
          <div className={styles.experienceList} role="list">
            {experience.map((exp) => (
              <ExperienceCard key={exp.id} experience={exp} />
            ))}
          </div>
        </section>

        {/* 项目经验 */}
        <section className={styles.section} aria-labelledby="projects-title">
          <h2 id="projects-title" className={styles.sectionTitle}>项目经验</h2>
          <div className={styles.projectsGrid} role="list">
            {projects.map((project, index) => (
              <ProjectCard key={project.id || `project-${index}`} project={project} />
            ))}
          </div>
        </section>

        {/* 教育背景 */}
        <section className={styles.section} aria-labelledby="education-title">
          <h2 id="education-title" className={styles.sectionTitle}>教育背景</h2>
          <div className={styles.educationList} role="list">
            {education.map((edu) => (
              <EducationCard key={edu.id} education={edu} />
            ))}
          </div>
        </section>
      </div>
    </main>
  );
};

export default Resume;
